<?php
namespace app\controller;

use app\BaseController;

use think\facade\Db;
use think\Request;
use think\captcha\facade\Captcha;
use think\cache\driver\Redis;
use think\facade\Cache;
use think\facade\Log;

/**
* 活动接口
* 20210720
*/
class Activity extends BaseController
{
	protected $userInfo;
	protected $request;
	protected $token;
	public function __construct(Request $request){
        $this->request = $request;
        $this->token = $this->request->header('token');
        $requests = new Request_type();
        if($this->token){
            $this->userInfo = $requests->getUserInfo($this->token);
        }
        
	}

	/**
	 * 活动列表
	 * @return json_encode([type] [description]
	 */
	public function index(){
	    $data = $this->request->param();
		$page = $data['page']?$data['page']:1;
	    $pageSize = $data['pageSize']?$data['pageSize']:10;
	    $list = Db::table("t_purchase")->order('id', 'desc')->page($page,$pageSize)->select()->toArray();
	    if($list){
	        foreach ($list as $k=>$v){
	            $list[$k]['start_time'] = strtotime($v['start_time']);
	            $list[$k]['end_time'] = strtotime($v['end_time'])+$v['delay'];
	            $list[$k]['sy'] = $v['quantity'] - ($v['amount']/$v['price']);
	        }
	    }
	    return json_encode(array("code"=>200,"msg"=>'成功','data'=>$list));
	}

	/**
	 * 活动信息
	 * @return json_encode([type] [description]
	 */
	public function details(){
	    $data = $this->request->param();
		$id = $data['id']?$data['id']:1;
		if($id == 0){
			return json_encode(array("code"=>'118',"msg"=>'請選擇要查看的活動'));
		}
		$list = Db::table("t_purchase")->where("id",$id)->find();
		if(!$data){
			return json_encode(array("code"=>'119',"msg"=>'請選擇正確的活動'));
		}
	    return json_encode(array("code"=>200,"msg"=>'成功','data'=>$list));

	}

	/**
	 * 活动规则详情
	 * @return json_encode([type] [description]
	 */
	public function rules(){

	}

	/**
	 * 参加活动
	 * @return json_encode([type] [description]
	 */
	public function participate(){	
	    if(!$this->token || $this->token == null){
            return json_encode(array("code"=>300,"msg"=>'TOKEN异常'));
        }
	    if(!$this->userInfo){
            return json_encode(array("code"=>301,"msg"=>'登入异常'));
        }
		$data = $this->request->param();
		$redis = new Redis();
        $redis->handler()->select(10);
		$activity_config = $redis->get('yt_activity');
		$activity_config = json_decode($activity_config,true);
		$activity = Db::table("t_purchase")->where("id",$data['id'])->where("status",1)->find();
		if(!$activity){
			return json_encode(array("code"=>'120',"msg"=>'該活動未開始或已結束'));
		}
		if(strtotime($activity['end_time']) + $activity['delay'] < time()){
		    return json_encode(array("code"=>'120',"msg"=>'該活動已結束'));
		}
		if($activity['amount'] + $data['money'] > $activity['quantity'] * $activity['price']){
		    return json_encode(array("code"=>'131',"msg"=>'投資金額超過上限'));
		}
		if(md5(md5($data['pay_password'].$this->userInfo['pay_salt'])) != $this->userInfo['pay_password']){
		    return json_encode(array("code"=>'124',"msg"=>'支付密碼錯誤'));
		}
		$balance = Db::table("t_user_coin")->where("user_id",$this->userInfo['id'])->where("coin_name",'USDT')->value('available_balance');
		if($balance < $data['money']){
			return json_encode(array("code"=>'116',"msg"=>'餘額不足'));
		}
		if($data['money']%$activity['price'] != 0 || $data['money'] <= 0){
		    return json_encode(array("code"=>'125',"msg"=>'投資金額不規範必須為整數倍'));
		}else{
		    $num = $data['money']/$activity['price'];
		}
		$num = $data['money']/$activity['price'];
		Db::startTrans();
		try {
			$userAct = Db::table("t_purchase_user")->where("user_id",$this->userInfo['id'])->where("p_id",$data['id'])->find();
			$max = $activity['quantity'] * $activity['price'] * $activity_config['max'];
			if($userAct){
			    $mo = Db::table("t_purchase_user")->where("user_id",$this->userInfo['id'])->where("p_id",$data['id'])->sum("number");
				if($mo + $data['money'] > $max && $this->userInfo['id'] > 5){
					return json_encode(array("code"=>'121',"msg"=>'個人投資超過上限!'));
				}
				// Db::table("t_purchase_user")->where("user_id",$this->userInfo['id'])->where("p_id",$data['id'])->update(['number'=>$data['money']+$userAct['number'],'last_time'=>date("Y-m-d H:i:s")]); -- 以前修改投资上限
			}else{
				if($data['money'] > $max  && $this->userInfo['id'] > 5){
					return json_encode(array("code"=>'121',"msg"=>'個人投資超過上限!!'));
				}
				$pu['sign_number'] = $activity['sign_number'] + 1;
				if($activity['delay'] + 60 < 86400){
				    $pu['delay'] = $activity['delay'] + 60;
				}
			}
            
            $participate = array(
				'p_id'=>$data['id'],
				'user_id'=>$this->userInfo['id'],
				'number'=>$data['money'],
				'ctime'=>date("Y-m-d H:i:s"),
				'last_time'=>date("Y-m-d H:i:s")
			);
			Db::table("t_purchase_user")->insert($participate);
			$p_u_id = Db::name('t_purchase_user')->getLastInsID();
			$bill=array(
				'user_id'=>$this->userInfo['id'],
				'coin_name'=>'USDT',
				'sub_type'=>0,
				'reason'=>'participate',
				'change_amount'=>-$data['money'],
				'comment'=>'用戶投資蟻團，當前期數ID：'.$data['id'],
				'last_time'=>date("Y-m-d H:i:s")
			);
			$pu['status'] = 1;
			if($activity['quantity'] * $activity['price'] == $activity['amount'] + $data['money']){
				$pu['status'] = 2;
				if(date('H') <= 7){
				    $strat_time = date("Y-m-d 9:00:00",time());
				    $end_time = date("Y-m-d H:i:00",strtotime($strat_time)+$activity_config['next']*60*60+86400);
				}else{
				    $strat_time = date("Y-m-d H:i:00",time()+$activity_config['next']*60*60);
				    $end_time = date("Y-m-d H:i:00",time()+$activity_config['next']*60*60+86400);
				}
				$purchase = array(
					"coin_name"=>'USDT',
					"start_time"=>$strat_time,
					"end_time"=>$end_time,
					"delay"=>0,
					"quantity"=>$activity['quantity'] + ceil($activity['quantity']*$activity_config['increase']),
					"sign_number"=>0,
					"price"=>$activity_config['money'],
					"amount"=>0,
					"ctime"=>date("Y-m-d H:i:s"),
					"status"=>0
				);
				Db::table("t_purchase")->insert($purchase);
				$p_id = Db::table("t_purchase")->getLastInsID();
			}
			$pu['amount'] = $activity['amount'] + $data['money'];
			Db::table("t_purchase")->where("id",$data['id'])->save($pu);
			for($i=0;$i<$num;$i++){
			    if(Db::table("t_purchase_user_details".$data['id'])->save(
			        array(
			            'user_id'=>$this->userInfo['id'],
			            'p_u_id'=>$p_u_id
			        )
			    )){
			        
			    }else{
			        Db::rollback();
			        return json_encode(array("code"=>100,"msg"=>'失敗','data'=>$e));
			    }
			 //   if(Db::query("show tables like `t_purchase_user_details`".$data['id'])){
			 //       if(Db::table("t_purchase_user_details".$data['id'])->save(
    // 			        array(
    // 			            'user_id'=>$this->userInfo['id'],
    // 			            'p_u_id'=>$p_u_id
    // 			        )
    // 			    )){
    			        
    // 			    }else{
    // 			        Db::rollback();
    // 			        return json_encode(array("code"=>100,"msg"=>'失敗','data'=>$e));
    // 			    }
			 //   }else{
			 //       $sql = "CREATE TABLE `t_purchase_user_details".$data['id']."`  (
    //                       `id` int(11) NOT NULL AUTO_INCREMENT,
    //                       `user_id` int(11) NOT NULL COMMENT '用户UID',
    //                       `p_u_id` int(11) NOT NULL COMMENT '参与报名序号ID',
    //                       PRIMARY KEY (`id`) USING BTREE
    //                     ) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact";
    //                 Db::query($sql);
    //                 if(Db::table("t_purchase_user_details".$data['id'])->save(
    // 			        array(
    // 			            'user_id'=>$this->userInfo['id'],
    // 			            'p_u_id'=>$p_u_id
    // 			        )
    // 			    )){
    			        
    // 			    }else{
    // 			        Db::rollback();
    // 			        return json_encode(array("code"=>100,"msg"=>'失敗','data'=>$e));
    // 			    }
			 //   }
    			    
			}
			Db::table('t_user_coin')->where("user_id",$this->userInfo['id'])->update(['available_balance'=>$balance-$data['money']]);
			Db::table("t_user_bill")->insert($bill);
            if($pu['status'] == 2){
                $sql = "CREATE TABLE `t_purchase_user_details".$p_id."`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL COMMENT '用户UID',
  `p_u_id` int(11) NOT NULL COMMENT '参与报名序号ID',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact";
                Db::query($sql);
            }
			Db::commit();
			return json_encode(array("code"=>200,"msg"=>'成功'));
		}catch (\Exception $e) {
		    // 回滚事务
		    Db::rollback();
		  //  Log::info('插入数据库失敗'.$e);
		    return json_encode(array("code"=>100,"msg"=>'失敗','data'=>$e));
		}
		
	}
	
}